package net.vsame.url2sql.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

import com.alibaba.fastjson.JSONObject;

/**
 * 2012-10-11 下午10:01:44
 * @author <a href="mailto:gaollg@sina.com">Gaollg</a>
 */
public class ConnectionUtils {
	
	private static String className = "com.mysql.jdbc.Driver";
	private static String url = null;
	private static String username = null;
	private static String password = null;
	
	static {
		try {
			Class.forName(className);
		} catch (ClassNotFoundException e) {
			throw new RuntimeException(e.getMessage());
		}
		
		String json = java.lang.System.getenv("VCAP_SERVICES");
		String dbname,host,port;
		if(json==null || "".equals(json)){
			dbname = "url2sql";
			username = "root";
			password = "root";
			host = "localhost";
			port = "3306";
		}else{
			JSONObject credentials = JSONObject.parseObject(json).getJSONArray("mysql-5.1").getJSONObject(0).getJSONObject("credentials");
			dbname =  credentials.getString("name");
		    username = credentials.getString("username");
			password = credentials.getString("password");
			host = credentials.getString("host");
			port = credentials.getString("port");
		}
		url = "jdbc:mysql://" + host + ":" + port + "/" + dbname;
	}
	
	/**
	 * 取得连接
	 * @param url
	 * @param username
	 * @param password
	 * @return
	 */
	public static Connection getConnection(String url, String username, String password){
		Connection conn = null;
		try {
			conn = DriverManager.getConnection(url, username, password);
		} catch (SQLException e) {
			throw new RuntimeException(e.getMessage());
		}
		return conn;
	}

	
	/**
	 * 从本地取得连接
	 * @return
	 */
	public static Connection getConnection(){
		return getConnection(url, username, password);
	}
	

}

